package gui;

import gui.browse.Browse;
import gui.browse.BrowseListener;
import gui.util.GUIUtils;
import gui.util.JFrameCadastro;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import model.Computador;
import model.Hardware;
import model.Periferico;
import model.Software;

import com.jgoodies.forms.layout.CellConstraints;

import controller.ComputadorController;
import controller.HardwareController;
import controller.PerifericoController;
import controller.SoftwareController;

public class ComputadorGUI extends JFrameCadastro{
	private static final long serialVersionUID = 1L;

	private JPanel panelCabecalho;
	private JPanel panelCentral;
	private JTextField editCodigo;
	private JTextField editDescricao;
	private JTextField editEnderecoMac;
	private JTextField editEnderecoIp;
	private JTextField editSistemaOperacional;
	private JTextField editSistemaOperacionalID;

	private Collection<JCheckBox> checkHardwares;
	private Collection<JCheckBox> checkSoftwares;
	private Collection<JCheckBox> checkPerifericos;

	private JButton botaoSistemaOperacional;

	private Collection<Hardware> hardwares;
	private Collection<Software> softwares;
	private Collection<Periferico> perifericos;

	public ActionListener actionIncluir;
	public ActionListener actionAlterar;
	public ActionListener actionExcluir;
	public ActionListener actionCancelar;
	public ActionListener actionGravar;



	public void initComponents(){
		this.setLayout(new BorderLayout());
		this.add(getPanelCabecalho(), BorderLayout.NORTH);
		this.add(getPanelCentral(), BorderLayout.CENTER);
		this.add(getPanelRodape(), BorderLayout.SOUTH);

		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		this.setResizable(false);
		pack();
		centralizar();
		this.setVisible(true);
	}

	public void centralizar() {
		Dimension so = Toolkit.getDefaultToolkit().getScreenSize();
		this.setLocation( 
				(( so.width-this.getSize().width ) / 2) , 
				(( so.height-this.getSize().height ) / 2 ) );  
	}



	public JPanel getPanelCabecalho() {
		if (panelCabecalho == null){
			panelCabecalho = new JPanel(GUIUtils.getLayout(7, 17));
			CellConstraints  cc = new CellConstraints();

			panelCabecalho.add(new JLabel("Codigo"),		cc.xywh(  2, 4,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCabecalho.add(getEditCodigo(),			cc.xywh( 10, 4,  5, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCabecalho.add(getBotaoBrowse(),			cc.xywh( 16, 4,  2, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCabecalho.add(new JLabel("Descricao"),	cc.xywh(  2, 6,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCabecalho.add(getEditDescricao(),		cc.xywh( 10, 6, 19, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCabecalho.add(new JLabel("Endereco Mac"),cc.xywh(  2, 8,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCabecalho.add(getEditEnderecoMac(),		cc.xywh( 10, 8, 19, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCabecalho.add(new JLabel("Endereco Ip"),	cc.xywh(  2,10,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCabecalho.add(getEditEnderecoIp(),		cc.xywh( 10,10, 19, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCabecalho.add(new JLabel("Sist. Operac."),	cc.xywh(  2, 12,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCabecalho.add(getEditSistemaOperacional(),cc.xywh( 10, 12,  5, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));
			panelCabecalho.add(getEditSistemaOperacionalID(),cc.xywh( 16, 12,  3, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));
			panelCabecalho.add(getBotaoSistemaOperacional(),cc.xywh( 20, 12,  2, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));
			

		}
		return panelCabecalho;
	}


	public JPanel getPanelCentral() {
		if (panelCentral == null){
			panelCentral = new JPanel();

			JPanel panelHardwares = new JPanel();
			panelHardwares.setBorder(new TitledBorder("Hardwares"));
			panelHardwares.setPreferredSize(new Dimension(150, 150));

			JPanel panelHardInterior = new JPanel(); 
			panelHardInterior.setPreferredSize(new Dimension(120, 120));
			panelHardInterior.setBorder(null);
			for (JCheckBox checkHardware : getCheckHardwares()) {
				checkHardware.setEnabled(false);
				panelHardInterior.add(checkHardware);
			}

			panelHardwares.add(new JScrollPane(panelHardInterior, 
					JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));

			JPanel panelSoftwares = new JPanel();
			panelSoftwares.setBorder(new TitledBorder("Softwares"));
			panelSoftwares.setPreferredSize(new Dimension(150, 150));
			panelSoftwares.setSize(40, 100);
			for (JCheckBox checkSoftware: getCheckSoftwares()) {
				checkSoftware.setEnabled(false);
				panelSoftwares.add(checkSoftware);
			}

			JPanel panelPerifericos = new JPanel();
			panelPerifericos.setBorder(new TitledBorder("Perifericos"));
			panelPerifericos.setPreferredSize(new Dimension(150, 150));
			panelPerifericos.setSize(40, 40);
			for (JCheckBox checkPeriferico : getCheckPerifericos()) {
				checkPeriferico.setEnabled(false);
				panelPerifericos.add(checkPeriferico);
			}

			panelCentral.add(panelHardwares);
			panelCentral.add(panelSoftwares);
			panelCentral.add(panelPerifericos);

		}
		return panelCentral;
	}

	public JTextField getEditCodigo() {
		if (editCodigo == null){
			editCodigo = new JTextField();
			editCodigo.setEditable(false);
			editCodigo.addKeyListener(new KeyAdapter() {
				public void keyPressed(KeyEvent key) {
					if (key.getKeyCode() == KeyEvent.VK_ENTER){
						if (editCodigo.getText() != null && !editCodigo.getText().trim().isEmpty()){
							if (!editCodigo.getText().trim().equals("0")){
								try {
									limparChecks();
									Computador pc = ComputadorController.getInstance().buscarComputadorPorId(Integer.valueOf(editCodigo.getText().trim()));
									getEditDescricao().setText(pc.getDescricao());
									getEditEnderecoIp().setText(pc.getEnderecoIp());
									getEditEnderecoMac().setText(pc.getEnderecoMac());
									getEditSistemaOperacional().setText(""+pc.getSistemaOperacional().getId());

									for (Hardware hard : pc.getHardwares()) {
										for (JCheckBox check : getCheckHardwares()) {
											if (check.getText().equals(hard.getDescricao())){
												check.setSelected(true);
											}
										}
									}

									for (Software soft : pc.getSoftwares()) {
										for (JCheckBox check : getCheckSoftwares()) {
											if (check.getText().equals(soft.getDescricao())){
												check.setSelected(true);
											}
										}
									}

									for (Periferico perif : pc.getPerifericos()) {
										for (JCheckBox check : getCheckPerifericos()) {
											if (check.getText().equals(perif.getDescricao())){
												check.setSelected(true);
											}
										}
									}
								} catch (NumberFormatException e) {
									e.printStackTrace();
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}
					}
				}
			});
		}
		return editCodigo;
	}


	public JTextField getEditDescricao() {
		if (editDescricao == null){
			editDescricao = new JTextField();
			editDescricao.setEnabled(false);
		}
		return editDescricao;
	}

	public JTextField getEditEnderecoMac() {
		if (editEnderecoMac == null){
			editEnderecoMac = new JTextField();
			editEnderecoMac.setEnabled(false);
		}
		return editEnderecoMac;
	}

	public JTextField getEditEnderecoIp() {
		if (editEnderecoIp == null){
			editEnderecoIp = new JTextField();
			editEnderecoIp.setEnabled(false);
		}
		return editEnderecoIp;
	}

	public JTextField getEditSistemaOperacional() {
		if (editSistemaOperacional == null){
			editSistemaOperacional = new JTextField();
			editSistemaOperacional.setEditable(false);
			editSistemaOperacional.setEnabled(false);
		}
		return editSistemaOperacional;
	}
	
	public JTextField getEditSistemaOperacionalID(){
		if(editSistemaOperacionalID == null){
			editSistemaOperacionalID = new JTextField();
			editSistemaOperacionalID.setEditable(false);
			editSistemaOperacionalID.setEnabled(false);
		}
		return editSistemaOperacionalID;
			
	}

	public JButton getBotaoSistemaOperacional() {
		if (botaoSistemaOperacional == null){
			botaoSistemaOperacional = new JButton("...");
			botaoSistemaOperacional.setEnabled(false);
			botaoSistemaOperacional.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					Browse browse = new Browse(SoftwareController.getInstance());
					browse.addBrowseListener(new BrowseListener() {
						
						@Override
						public void linhaClicada(HashMap<String, Object> dados) {
							getEditSistemaOperacional().setText((String) dados.get("descricao"));
							getEditSistemaOperacionalID().setText(String.valueOf(dados.get("codigo")));
							
						}
					});
					browse.getFocusableWindowState();
				}
			});

		}
		return botaoSistemaOperacional;
	}
	
	public JButton getBotaoBrowse(){
		return super.getBotaoBrowse(ComputadorController.getInstance());
	}


	@Override
	public ActionListener getActionIncluir() {
		if (actionIncluir == null){
			actionIncluir = new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					escreverRegistro(true);
					getEditCodigo().setText("0");
				}
			};	
		}
		return actionIncluir;
	}

	@Override
	public ActionListener getActionAlterar() {
		if (actionAlterar == null){
			actionAlterar = new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					escreverRegistro(true);
				}
			};
		}
		return actionAlterar;
	}

	@Override
	public ActionListener getActionExcluir() {
		if (actionExcluir == null){
			actionExcluir = new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					if (getEditCodigo().getText() != null && !getEditCodigo().getText().trim().isEmpty()){
						try {
							int opcao = (JOptionPane.showConfirmDialog(null, "Tem certeza que deseja excluir o registro "+ getEditCodigo().getText() +"?",
									"T�tulo", JOptionPane.YES_NO_OPTION));
							if (opcao == JOptionPane.YES_OPTION) {
								ComputadorController.getInstance().excluirComputador((Integer.valueOf(getEditCodigo().getText().trim())));
								limparDados();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			};
		}
		return actionExcluir;
	}

	@Override
	public ActionListener getActionCancelar() {
		if (actionCancelar == null){
			actionCancelar = new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					limparDados();
					escreverRegistro(false);
				}
			};
		}
		return actionCancelar;
	}

	@Override
	public ActionListener getActionGravar() {
		if (actionGravar == null){
			actionGravar = new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					if (getEditCodigo().getText().trim() != null && !getEditCodigo().getText().trim().isEmpty()){
						if (getEditCodigo().getText().trim().equals("0")){
							try {
								ComputadorController.getInstance().inserirComputador( 
										getEditDescricao().getText(),
										getEditEnderecoMac().getText(), 
										getEditEnderecoIp().getText(), 
										Integer.valueOf(getEditSistemaOperacionalID().getText().trim()), 
										getHardwaresSelecionados(),
										getSoftwaresSelecionados(),
										getPerifericosSelecionados());

							} catch (Exception e) {
								e.printStackTrace();
							}
						} else {
							try {
								ComputadorController.getInstance().alterarComputador(
										Integer.valueOf(getEditCodigo().getText().trim()),
										getEditDescricao().getText(),
										getEditEnderecoMac().getText(), 
										getEditEnderecoIp().getText(), 
										Integer.valueOf(getEditSistemaOperacionalID().getText().trim()),
										getHardwaresSelecionados(),
										getSoftwaresSelecionados(),
										getPerifericosSelecionados());

							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
					escreverRegistro(false);
					limparDados();
					getBotaoFechar().grabFocus();
				}
			};
		}
		return actionGravar;
	}


	public Collection<JCheckBox> getCheckHardwares() {
		if (checkHardwares == null){
			checkHardwares = new ArrayList<JCheckBox>();
			for (Hardware hardware : getHardwares()) {
				checkHardwares.add(new JCheckBox(hardware.getDescricao()));
			}
		}
		return checkHardwares;
	}
	public Collection<JCheckBox> getCheckSoftwares() {
		if (checkSoftwares== null){
			checkSoftwares = new ArrayList<JCheckBox>();
			for (Software software : getSoftwares()) {
				checkSoftwares.add(new JCheckBox(software.getDescricao()));
			}
		}
		return checkSoftwares;
	}
	public Collection<JCheckBox> getCheckPerifericos() {
		if (checkPerifericos == null){
			checkPerifericos = new ArrayList<JCheckBox>();
			for (Periferico periferico: getPerifericos()) {
				checkPerifericos.add(new JCheckBox(periferico.getDescricao()));
			}
		}
		return checkPerifericos;
	}


	public Collection<Hardware> getHardwares(){
		if (hardwares == null){
			hardwares = new ArrayList<Hardware>();
			try {
				hardwares = HardwareController.getInstance().buscarTodos();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return hardwares;
	}
	public Collection<Software> getSoftwares(){
		if (softwares == null){
			softwares = new ArrayList<Software>();
			try {
				softwares = SoftwareController.getInstance().buscarTodos();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return softwares;
	}
	public Collection<Periferico> getPerifericos(){
		if (perifericos == null){
			perifericos = new ArrayList<Periferico>();
			try {
				perifericos = PerifericoController.getInstance().buscarTodos();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return perifericos;
	}

	public void escreverRegistro(boolean b){
		getBotaoCancelar().setEnabled(b);
		getBotaoGravar().setEnabled(b);
		getBotaoIncluir().setEnabled(!b);
		getBotaoAlterar().setEnabled(!b);
		getBotaoExcluir().setEnabled(!b);
		getBotaoFechar().setEnabled(!b);
		getBotaoBrowse().setEnabled(!b);
		getEditCodigo().setEnabled(b);
		getEditDescricao().setEnabled(b);
		getEditEnderecoIp().setEnabled(b);
		getEditEnderecoMac().setEnabled(b);
		getEditSistemaOperacional().setEnabled(b);
		getEditSistemaOperacionalID().setEnabled(b);
		getBotaoSistemaOperacional().setEnabled(b);
		panelCheck(b);
	}

	public void limparDados(){
		getEditCodigo().setText("");
		getEditDescricao().setText("");
		getEditEnderecoIp().setText("");
		getEditEnderecoMac().setText("");
		getEditSistemaOperacional().setText("");
		limparChecks();
	}

	public void limparChecks(){
		for (JCheckBox check : getCheckHardwares()) {
			check.setSelected(false);
		}
		for (JCheckBox check : getCheckSoftwares()) {
			check.setSelected(false);
		}
		for (JCheckBox check : getCheckPerifericos()) {
			check.setSelected(false);
		}
	}

	public void panelCheck(boolean b){
		for (JCheckBox check : getCheckHardwares()) {
			check.setEnabled(b);
		}
		for (JCheckBox check : getCheckSoftwares()) {
			check.setEnabled(b);
		}
		for (JCheckBox check : getCheckPerifericos()) {
			check.setEnabled(b);
		}
	}

	public Collection<String> getHardwaresSelecionados(){
		Collection<String> hard = new ArrayList<String>();
		for (JCheckBox check : getCheckHardwares()) {
			if (check.isSelected()){
				hard.add(check.getText());
			}
		}
		return hard;
	}

	public Collection<String> getSoftwaresSelecionados(){
		Collection<String> soft = new ArrayList<String>();
		for (JCheckBox check : getCheckSoftwares()) {
			if (check.isSelected()){
				soft.add(check.getText());
			}
		}
		return soft;
	}

	public Collection<String> getPerifericosSelecionados(){
		Collection<String> perf = new ArrayList<String>();
		for (JCheckBox check : getCheckPerifericos()) {
			if (check.isSelected()){
				perf.add(check.getText());
			}
		}
		return perf;
	}


	@Override
	public void preencherCampos(HashMap<String, Object> dados) {
		Computador pc = null;
		try {
			pc = ComputadorController.getInstance().buscarComputadorPorId( (Integer) dados.get("codigo"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		editCodigo.setText(String.valueOf(pc.getId()));
		editDescricao.setText(pc.getDescricao());
		editEnderecoMac.setText(pc.getEnderecoMac());
		editEnderecoIp.setText(pc.getEnderecoIp());
		editSistemaOperacional.setText(pc.getSistemaOperacional().getDescricao());
		editSistemaOperacionalID.setText(String.valueOf(pc.getSistemaOperacional().getId()));

	}
}